﻿using ClosedXML.Excel;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SmartProduction.Domain;
using SmartProduction.Domain.客户管理;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue;
using SmartProduction.Write.API.Application.Commands.ClientInfoCommand;
using SmartProduction.Write.API.Application.Commands.GodownEntryCommand;
using SmartProduction.Write.API.Application.Commands.MaterialInfoCommand;
using SmartProduction.Write.API.Application.Commands.ResourceInfoCommand;
using SmartProduction.Write.API.Application.Commands.SalesOrderCommand;
using SmartProduction.Write.API.Application.Commands.Work__CaigouOrderCommand;
using SmartProduction.Write.API.Application.Commands.work_InvoiceCommand;
using SmartProduction.Write.API.Application.Commands.work_SalesOrderCommand;
using WorkflowCore.Interface;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;

namespace SmartProduction.Write.API.Controllers
{
    /// <summary>
    /// API控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ResourceController : ControllerBase
    {
        /// <summary>
        /// 中介者
        /// </summary>
        private readonly IMediator mediator;
        private readonly IWorkflowHost workflowHost;
        private readonly DataDbContext db;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="mediator">中介者</param>
        public ResourceController(IMediator mediator, IWorkflowHost workflowHost,  DataDbContext db)
        {
            this.mediator = mediator;
            this.workflowHost = workflowHost;
            this.db = db;
        }

        /// <summary>
        /// 新增物料
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回</returns>
        [HttpPost]
        public Task<APIResult<object>> MaterialAdd(MaterialInfoCreateCommand command)
        {
            return mediator.Send(command);
        }

        /// <summary>
        /// 新增资源信息
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回</returns>
        [HttpPost]
        public async Task<APIResult<object>> ResourceAdd(ResourceInfoCreateCommand command)
        {
            return await mediator.Send(command);
        }

        /// <summary>
        /// 新增客户信息
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回</returns>
        [HttpPost]
        public Task<APIResult<object>> ClientAdd(ClientInfoCreateCommand command)
        {
            return mediator.Send(command);
        }

        /// <summary>
        /// 销售订单新增
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回</returns>
        [HttpPost]
        public Task<APIResult<object>> SalesOrderAdd(SalesOrderCrearteCommand command)
        {
            return mediator.Send(command);
        }

        /// <summary>
        /// 修改销售订单
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回</returns>
        [HttpPost]
        public async Task<APIResult<object>> SalesOrderUpd(SalesOrderUpdCommand command)
        {
            return await mediator.Send(command);
        }

        /// <summary>
        /// 导入客户信息
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> ImportInventories(IFormFile file)
        {
            APIResult<string> result = new APIResult<string>();
            try
            {
                // 检查上传文件是否为空
                if (file == null || file.Length <= 0)
                {
                    result.Code = APIEnums.查询失败;
                    result.Msg = "未上传文件或文件为空";
                    return BadRequest(result);
                }

                // 检查文件扩展名是否为 Excel 格式
                var fileExtension = Path.GetExtension(file.FileName);
                if (fileExtension != ".xlsx" && fileExtension != ".xls")
                {
                    result.Code = APIEnums.查询失败;
                    result.Msg = "仅支持上传 Excel 文件";
                    return BadRequest(result);
                }

                // 使用 MemoryStream 读取文件内容
                using (var stream = new MemoryStream())
                {
                    await file.CopyToAsync(stream);
                    using (var workbook = new XLWorkbook(stream))
                    {
                        var worksheet = workbook.Worksheet(1); // 获取第一个工作表
                        var rows = worksheet.RowsUsed().Skip(1); // 跳过第一行（表头）

                        List<ClientInfo> clie = new List<ClientInfo>();

                        foreach (var row in rows)
                        {
                            var clien = new ClientInfo();
                            clien.ClientInfoNo = row.Cell(1).GetValue<string>();
                            clien.ClientInfoNumer = row.Cell(2).GetValue<string>();
                            clien.ClientInfoName = row.Cell(3).GetValue<string>();
                            clien.ClientInfoType = row.Cell(4).GetValue<string>();
                            clien.ClientInfoPhone = row.Cell(5).GetValue<string>();
                            clien.ClientInfoEmail = row.Cell(6).GetValue<string>();
                            clien.IndustryId = row.Cell(7).GetValue<int>();
                            clien.ClientInfoAddr = row.Cell(8).GetValue<string>();
                            clien.CountryName = row.Cell(9).GetValue<string>();
                            clien.CountryCity = row.Cell(10).GetValue<int>();
                            clien.ClientInfoClass = row.Cell(11).GetValue<string>();
                            clien.ClientInfoLabel = row.Cell(12).GetValue<string>();
                            clien.ClientInfoStatu = row.Cell(13).GetValue<bool>();
                            clien.FirmLabel = row.Cell(14).GetValue<bool>();
                            clien.IsDelete = row.Cell(15).GetValue<bool>();

                            // 添加到要插入的列表中
                            clie.Add(clien);
                        }
                        await db.AddRangeAsync(clie);
                        await db.SaveChangesAsync();
                        result.Code = APIEnums.添加成功;
                        result.Msg = "导入成功";
                        result.data = clie.Count.ToString();
                    }
                }
            }
            catch (Exception ex)
            {

                result.Code = APIEnums.添加失败;
                result.Msg = "导入失败，原因：" + ex.Message;
                return StatusCode(500, result);
            }
            return Ok(result);
        }

        /// <summary>
        /// 入库单添加
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<APIResult<object>> GodoWnEntryAdd(GodownEntryCreateCommand command)
        {
            try
            {
                return await mediator.Send(command);
            }
            catch (Exception)
            {

                throw;
            }
        }


        /// <summary>
        /// 基础信息新增
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回</returns>
        [HttpPost]
        public Task<APIResult<object>> work_invoiceAdd(work_InvoiceCreateCommand command)
        {
            try
            {
                return mediator.Send(command);
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 销售订单新增
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回</returns>
        [HttpPost]
        public Task<APIResult<object>> work_SalesAdd(work_SalesOrderCreateCommand command)
        {
            try
            {
                return mediator.Send(command);
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 采购订单新增
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回</returns>
        [HttpPost]
        public Task<APIResult<object>> work_CaigouAdd(Work__CaigouOrderCreateCommand command)
        {
            try
            {
                return mediator.Send(command);

            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 销售订单删除
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回任务</returns>
        [HttpPost]
        public async Task<APIResult<object>> workSalesDelete(work_SalesOrderDelCommand command)
        {
            try
            {
                return await mediator.Send(command);
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
